//
//  HomeViewController.m
//  Tang
//
//  Created by 352324497@qq.com on 15/12/3.
//  Copyright © 2015年 邓芮. All rights reserved.
//

#import "HomeViewController.h"
#import "ScrollModel.h"
#import "CollectionModel.h"
#import "elementModel.h"
#import "TableCellModel.h"
#import "HomeViewCell.h"
#import "CollectionCell.h"
#import "ScrollViewCell.h"
#import "ScrollViewTableController.h"
#import "HomeDetailViewController.h"
#import "CollectionDetailViewController.h"
@interface HomeViewController ()<ScrollViewCellDelegate, collectionCellDelegate>
@property (nonatomic, strong)NSMutableDictionary *dictionary;
@property (nonatomic, strong)NSMutableArray *scrollArray;
@property (nonatomic, strong)NSMutableArray *elementArray;
@property (nonatomic, strong)NSMutableArray *collectionArray;
@property (nonatomic, strong)NSMutableArray *tableCellArray;
@property (nonatomic, strong)NSMutableArray *photosArray;
@property (nonatomic, assign)NSInteger Num;
@end

@implementation HomeViewController
-(NSMutableArray *)tableCellArray
{
    if (!_tableCellArray)
    {
        self.tableCellArray = [NSMutableArray array];
    }
    return _tableCellArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.tableView.separatorStyle = NO;
    self.Num = 0;
    self.dictionary = [NSMutableDictionary dictionary];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self.tableCellArray removeAllObjects];
               self.dictionary = [self requestHomeDataWithUrl:@"http://open3.bantangapp.com/recommend/index?app_installtime=1449053241.284786&app_versions=5.0&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&os_versions=9.1&page=0&pagesize=20&screensize=640&track_deviceid=1AA9E26F-492E-48AC-8FC0-3FFA9007E29F&v=8"];
        [self.tableView.mj_header endRefreshing];
    }];
    [self.tableView.mj_header beginRefreshing];
    
    self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        self.Num += 1;
        NSString *url = [NSString stringWithFormat:@"http://open3.bantangapp.com/recommend/index?app_installtime=1449053241.284786&app_versions=5.0&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&os_versions=9.1&page=%ld&pagesize=20&screensize=640&track_deviceid=1AA9E26F-492E-48AC-8FC0-3FFA9007E29F&v=8",self.Num];
        [self requestHomeDataWithUrl:url];
        
        [self.tableView.mj_footer endRefreshing];
    }];
}

-(NSMutableDictionary *)requestHomeDataWithUrl:(NSString *)url
{
    [[NetworkState shareInstance]reachablityStatesWithDongHua:self];
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
    [[[NSURLSession sharedSession]dataTaskWithURL:[NSURL URLWithString:url] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data == nil)
        {
            NSLog(@"数据请求失败");
            UIAlertAction *OKaction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self dismissViewControllerAnimated:YES completion:nil];
            }];
            UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"提示" message:@"亲, 网络好像不是很给力哦~~~" preferredStyle:(UIAlertControllerStyleAlert)];
            [alertView addAction:OKaction];
            [self presentViewController:alertView animated:YES completion:nil];
            [[NetworkState shareInstance] finshYYToVc:self];
            return ;
        }
        NSDictionary *Dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSDictionary *dataDic = Dic[@"data"];
        
        self.scrollArray = [NSMutableArray array];
        self.photosArray = [NSMutableArray array];
        for (NSDictionary *dic in dataDic[@"banner"])
        {
            ScrollModel *scrollModel = [[ScrollModel alloc]init];
            [scrollModel setValuesForKeysWithDictionary:dic];
            [self.photosArray addObject:scrollModel.photo];
            [self.scrollArray addObject:scrollModel];
        }
        [dictionary setValue:_scrollArray forKey:@"ScrollArray"];
        
        self.elementArray = [NSMutableArray array];
        for (NSDictionary *dic in dataDic[@"category_element"])
        {
            elementModel *eleModel = [[elementModel alloc]init];
            [eleModel setValuesForKeysWithDictionary:dic];
            [self.elementArray addObject:eleModel];
        }
        [dictionary setValue:_elementArray forKey:@"elementArray"];
        
        self.collectionArray = [NSMutableArray array];
        for (NSDictionary *dic in dataDic[@"entry_list"])
        {
            CollectionModel *collectionModel = [[CollectionModel alloc]init];
            [collectionModel setValuesForKeysWithDictionary:dic];
            [self.collectionArray addObject:collectionModel];
        }
        [dictionary setValue:_collectionArray forKey:@"collectionArray"];
        for (NSDictionary *dic in dataDic[@"topic"])
        {
            TableCellModel *tableCellModel = [[TableCellModel alloc]init];
            [tableCellModel setValuesForKeysWithDictionary:dic];
            [self.tableCellArray addObject:tableCellModel];
        }
        [dictionary setValue:_tableCellArray forKey:@"tableCellArray"];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.tableView reloadData]; // 刷新单元格
            [[NetworkState shareInstance]finshYYToVc:self];
        });
    }]resume];
    return dictionary;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if (section == 0)
    {
        return 1;
    }
    else if (section == 1)
    {
        return 1;
    }
    else
    {
        if (self.tableCellArray.count != 0)
        {
            return self.tableCellArray.count;
        }
        return 0;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        return KWidth * 586 / 900;
    }
    else if (indexPath.section == 1)
    {
        return 120 * Kx6;
    }
    return  KWidth * 330 / 620 + 80 * Kx6;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0)
    {
        ScrollViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"scrollCell"];
        if (cell == nil)
        {
            cell = [[ScrollViewCell alloc]initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:@"scrollCell"];
        }
        if (self.scrollArray.count != 0)
        {
            [cell setCellWithArray:self.photosArray];
        }
        cell.delegate = self;
        return cell;
    }
    else if (indexPath.section == 1)
    {
        CollectionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"collectionCell"];
        if (cell == nil)
        {
            cell = [[CollectionCell alloc]initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:@"collectionCell"];
        }
        if (self.collectionArray.count != 0)
        {
            [cell setCellWithArray:self.collectionArray];
        }
        cell.delegate = self;
        return cell;
    }
    else
    {
        HomeViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"homeCell"];
        if (cell == nil)
        {
            cell = [[HomeViewCell alloc]initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:@"homeCell"];
        }
        if (self.tableCellArray.count != 0)
        {
            TableCellModel *model = self.tableCellArray[indexPath.row];
            cell.model = model;
        }
        
        return cell;
    }
    
    
    return nil;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TableCellModel *model = self.tableCellArray[indexPath.row];
    HomeDetailViewController *homeDeVc = [[HomeDetailViewController alloc] init];
    homeDeVc.PinJieId = model.Id;
    
    HomeViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
    homeDeVc.headerImage = cell.picImageView.image;
    [self.navigationController pushViewController:homeDeVc animated:YES];
    
}

#pragma mark - ScrollView的代理方法
-(void)jumpPageWithIndex:(NSInteger)index
{
    if (self.scrollArray != 0)
    {
        ScrollModel *model = self.scrollArray[index];
        ScrollViewTableController *scrollViewVc = [[ScrollViewTableController alloc]initWithStyle:(UITableViewStylePlain)];
        scrollViewVc.extend = model.extend;
        scrollViewVc.name = model.title;
        NSString *str = [scrollViewVc.extend substringToIndex:4];
        if ([str isEqualToString:@"http"])
        {
            
        }
        else
        {
            [self.navigationController pushViewController:scrollViewVc animated:YES];
        }
    }
    
}

-(void)jumpToControllerWithIndexPath:(NSIndexPath *)indexPath
{
    CollectionDetailViewController *collectionViewVc = [[CollectionDetailViewController alloc]init];
    CollectionModel *model = self.collectionArray[indexPath.item];
    collectionViewVc.Id = model.Id;
    [self.navigationController pushViewController:collectionViewVc animated:NO];
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
